const express = require('express');
const fs = require('fs');
const path = require('path');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

// 应用数据文件路径
const APPS_DATA_PATH = path.join(__dirname, 'data', 'apps.json');

// 确保数据目录存在
if (!fs.existsSync(path.join(__dirname, 'data'))) {
    fs.mkdirSync(path.join(__dirname, 'data'));
}

// 初始化应用数据（如果不存在）
if (!fs.existsSync(APPS_DATA_PATH)) {
    const initialApps = [
        {
            id: 1,
            name: "微信",
            icon: "https://picsum.photos/seed/wechat/100",
            description: "全方位的社交与通讯工具，连接你我",
            version: "8.0.45",
            updateDate: "2025-08-20",
            downloads: 356240,
            category: "social",
            officialUrl: "https://weixin.qq.com/",
            platform: ["android", "ios"]
        },
        {
            id: 2,
            name: "QQ",
            icon: "https://picsum.photos/seed/qq/100",
            description: "年轻人喜爱的社交平台，多样互动方式",
            version: "9.9.9",
            updateDate: "2025-08-18",
            downloads: 289150,
            category: "social",
            officialUrl: "https://im.qq.com/",
            platform: ["android", "ios"]
        },
        {
            id: 3,
            name: "支付宝",
            icon: "https://picsum.photos/seed/alipay/100",
            description: "安全便捷的移动支付与生活服务平台",
            version: "10.5.30",
            updateDate: "2025-08-22",
            downloads: 245680,
            category: "shopping",
            officialUrl: "https://www.alipay.com/",
            platform: ["android", "ios"]
        },
        {
            id: 4,
            name: "抖音",
            icon: "https://picsum.photos/seed/douyin/100",
            description: "记录美好生活的短视频平台",
            version: "25.8.0",
            updateDate: "2025-08-25",
            downloads: 421560,
            category: "entertainment",
            officialUrl: "https://www.douyin.com/",
            platform: ["android", "ios"]
        },
        {
            id: 5,
            name: "淘宝",
            icon: "https://picsum.photos/seed/taobao/100",
            description: "综合网购平台，海量商品任你选",
            version: "10.12.0",
            updateDate: "2025-08-15",
            downloads: 198750,
            category: "shopping",
            officialUrl: "https://www.taobao.com/",
            platform: ["android", "ios"]
        },
        {
            id: 6,
            name: "京东",
            icon: "https://picsum.photos/seed/jd/100",
            description: "专业的综合网上购物商城",
            version: "12.3.0",
            updateDate: "2025-08-17",
            downloads: 156230,
            category: "shopping",
            officialUrl: "https://www.jd.com/",
            platform: ["android", "ios"]
        },
        {
            id: 7,
            name: "百度",
            icon: "https://picsum.photos/seed/baidu/100",
            description: "智能搜索，让信息触手可及",
            version: "13.8.0",
            updateDate: "2025-08-21",
            downloads: 187620,
            category: "tools",
            officialUrl: "https://www.baidu.com/",
            platform: ["android", "ios"]
        },
        {
            id: 8,
            name: "高德地图",
            icon: "https://picsum.photos/seed/amap/100",
            description: "专业的手机地图，导航更精准",
            version: "12.1.0",
            updateDate: "2025-08-14",
            downloads: 145890,
            category: "tools",
            officialUrl: "https://www.amap.com/",
            platform: ["android", "ios"]
        },
        {
            id: 9,
            name: "腾讯视频",
            icon: "https://picsum.photos/seed/tencentvideo/100",
            description: "海量影视内容，高清流畅播放",
            version: "11.8.0",
            updateDate: "2025-08-24",
            downloads: 210350,
            category: "entertainment",
            officialUrl: "https://v.qq.com/",
            platform: ["android", "ios"]
        },
        {
            id: 10,
            name: "爱奇艺",
            icon: "https://picsum.photos/seed/iqiyi/100",
            description: "优质视频娱乐平台，精彩内容不断",
            version: "14.6.0",
            updateDate: "2025-08-19",
            downloads: 178450,
            category: "entertainment",
            officialUrl: "https://www.iqiyi.com/",
            platform: ["android", "ios"]
        },
        {
            id: 11,
            name: "网易云音乐",
            icon: "https://picsum.photos/seed/neteasemusic/100",
            description: "发现好音乐，听见好时光",
            version: "9.8.0",
            updateDate: "2025-08-23",
            downloads: 165980,
            category: "entertainment",
            officialUrl: "https://music.163.com/",
            platform: ["android", "ios"]
        },
        {
            id: 12,
            name: "微博",
            icon: "https://picsum.photos/seed/weibo/100",
            description: "发现新鲜事，分享生活点滴",
            version: "13.6.0",
            updateDate: "2025-08-16",
            downloads: 201560,
            category: "social",
            officialUrl: "https://weibo.com/",
            platform: ["android", "ios"]
        },
        {
            id: 13,
            name: "哔哩哔哩",
            icon: "https://picsum.photos/seed/bilibili/100",
            description: "二次元文化社区，海量原创内容",
            version: "7.5.0",
            updateDate: "2025-08-26",
            downloads: 198750,
            category: "entertainment",
            officialUrl: "https://www.bilibili.com/",
            platform: ["android", "ios"]
        },
        {
            id: 14,
            name: "小红书",
            icon: "https://picsum.photos/seed/xiaohongshu/100",
            description: "生活方式分享社区，发现美好事物",
            version: "7.8.0",
            updateDate: "2025-08-13",
            downloads: 156320,
            category: "social",
            officialUrl: "https://www.xiaohongshu.com/",
            platform: ["android", "ios"]
        },
        {
            id: 15,
            name: "美团",
            icon: "https://picsum.photos/seed/meituan/100",
            description: "吃喝玩乐一站式生活服务平台",
            version: "12.5.20",
            updateDate: "2025-08-27",
            downloads: 234560,
            category: "life",
            officialUrl: "https://www.meituan.com/",
            platform: ["android", "ios"]
        },
        {
            id: 16,
            name: "饿了么",
            icon: "https://picsum.photos/seed/eleme/100",
            description: "专业的外卖服务平台，美食送到家",
            version: "10.11.0",
            updateDate: "2025-08-12",
            downloads: 187650,
            category: "life",
            officialUrl: "https://www.ele.me/",
            platform: ["android", "ios"]
        },
        {
            id: 17,
            name: "滴滴出行",
            icon: "https://picsum.photos/seed/didi/100",
            description: "便捷的出行平台，一键叫车",
            version: "6.5.0",
            updateDate: "2025-08-28",
            downloads: 145620,
            category: "life",
            officialUrl: "https://www.didiglobal.com/",
            platform: ["android", "ios"]
        },
        {
            id: 18,
            name: "钉钉",
            icon: "https://picsum.photos/seed/dingding/100",
            description: "高效办公沟通平台，提升团队协作",
            version: "7.3.0",
            updateDate: "2025-08-11",
            downloads: 123450,
            category: "tools",
            officialUrl: "https://www.dingtalk.com/",
            platform: ["android", "ios"]
        },
        {
            id: 19,
            name: "拼多多",
            icon: "https://picsum.photos/seed/pinduoduo/100",
            description: "社交电商平台，拼团更优惠",
            version: "6.8.0",
            updateDate: "2025-08-10",
            downloads: 210980,
            category: "shopping",
            officialUrl: "https://www.pinduoduo.com/",
            platform: ["android", "ios"]
        },
        {
            id: 20,
            name: "优酷",
            icon: "https://picsum.photos/seed/youku/100",
            description: "海量影视内容，高清品质享受",
            version: "10.9.0",
            updateDate: "2025-08-09",
            downloads: 165430,
            category: "entertainment",
            officialUrl: "https://www.youku.com/",
            platform: ["android", "ios"]
        },
        {
            id: 21,
            name: "酷狗音乐",
            icon: "https://picsum.photos/seed/kugou/100",
            description: "高品质音乐播放，百万曲库任你听",
            version: "11.2.0",
            updateDate: "2025-08-08",
            downloads: 132560,
            category: "entertainment",
            officialUrl: "https://www.kugou.com/",
            platform: ["android", "ios"]
        },
        {
            id: 22,
            name: "快手",
            icon: "https://picsum.photos/seed/kuaishou/100",
            description: "记录和分享生活的短视频平台",
            version: "11.6.0",
            updateDate: "2025-08-07",
            downloads: 245670,
            category: "entertainment",
            officialUrl: "https://www.kuaishou.com/",
            platform: ["android", "ios"]
        }
    ];
    
    fs.writeFileSync(APPS_DATA_PATH, JSON.stringify(initialApps, null, 2));
}

// 读取应用数据
const readAppsData = () => {
    try {
        const data = fs.readFileSync(APPS_DATA_PATH, 'utf8');
        return JSON.parse(data);
    } catch (err) {
        console.error('Error reading apps data:', err);
        return [];
    }
};

// 保存应用数据
const saveAppsData = (data) => {
    try {
        fs.writeFileSync(APPS_DATA_PATH, JSON.stringify(data, null, 2));
        return true;
    } catch (err) {
        console.error('Error saving apps data:', err);
        return false;
    }
};

// API 路由
app.get('/api/apps', (req, res) => {
    const apps = readAppsData();
    const { category, search, page = 1, limit = 12 } = req.query;
    
    // 过滤应用
    let filteredApps = [...apps];
    
    // 按分类过滤
    if (category && category !== 'all') {
        filteredApps = filteredApps.filter(app => app.category === category);
    }
    
    // 搜索过滤
    if (search) {
        const searchLower = search.toLowerCase();
        filteredApps = filteredApps.filter(app => 
            app.name.toLowerCase().includes(searchLower) || 
            app.description.toLowerCase().includes(searchLower)
        );
    }
    
    // 分页
    const startIndex = (page - 1) * limit;
    const paginatedApps = filteredApps.slice(startIndex, startIndex + parseInt(limit));
    
    res.json({
        apps: paginatedApps,
        total: filteredApps.length,
        page: parseInt(page),
        pages: Math.ceil(filteredApps.length / limit)
    });
});

app.get('/api/apps/:id', (req, res) => {
    const apps = readAppsData();
    const app = apps.find(a => a.id === parseInt(req.params.id));
    
    if (app) {
        res.json(app);
    } else {
        res.status(404).json({ message: '应用未找到' });
    }
});

// 更新应用下载计数
app.post('/api/apps/:id/download', (req, res) => {
    const apps = readAppsData();
    const appIndex = apps.findIndex(a => a.id === parseInt(req.params.id));
    
    if (appIndex !== -1) {
        apps[appIndex].downloads += 1;
        saveAppsData(apps);
        res.json({ success: true, downloads: apps[appIndex].downloads });
    } else {
        res.status(404).json({ message: '应用未找到' });
    }
});

// 获取统计数据
app.get('/api/stats', (req, res) => {
    const apps = readAppsData();
    
    // 计算总下载量
    const totalDownloads = apps.reduce((sum, app) => sum + app.downloads, 0);
    
    // 今日更新数（最近24小时）
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const todayUpdates = apps.filter(app => new Date(app.updateDate) >= today).length;
    
    // 按分类统计
    const categoryStats = {};
    apps.forEach(app => {
        if (!categoryStats[app.category]) {
            categoryStats[app.category] = 0;
        }
        categoryStats[app.category]++;
    });
    
    // 生成最近30天的下载趋势数据（模拟）
    const downloadTrend = [];
    for (let i = 29; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
        
        // 生成模拟数据
        const base = 20000;
        const fluctuation = Math.floor(Math.random() * 10000) - 5000;
        
        downloadTrend.push({
            date: dateStr,
            downloads: base + fluctuation
        });
    }
    
    res.json({
        totalApps: apps.length,
        totalDownloads,
        todayUpdates,
        activeUsers: Math.floor(Math.random() * 10000) + 40000, // 模拟活跃用户
        categoryStats,
        downloadTrend
    });
});

// 模拟定期更新应用版本（实际环境中可以使用定时任务）
app.post('/api/update-versions', (req, res) => {
    const apps = readAppsData();
    const updatedApps = apps.map(app => {
        // 随机更新一部分应用
        if (Math.random() < 0.3) {
            // 简单版本号递增逻辑
            const versionParts = app.version.split('.').map(Number);
            versionParts[versionParts.length - 1] += 1;
            
            return {
                ...app,
                version: versionParts.join('.'),
                updateDate: new Date().toISOString().split('T')[0]
            };
        }
        return app;
    });
    
    const success = saveAppsData(updatedApps);
    res.json({ success, updatedCount: updatedApps.filter((app, i) => app.version !== apps[i].version).length });
});

// 提供前端页面
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
    console.log('应用数据将定期更新以确保链接有效性');
});

// 定时任务：每天检查并更新应用信息（模拟）
setInterval(() => {
    console.log('定期检查并更新应用信息...');
    const apps = readAppsData();
    const updatedApps = apps.map(app => {
        // 随机更新一部分应用
        if (Math.random() < 0.1) { // 10% 的概率更新
            // 简单版本号递增逻辑
            const versionParts = app.version.split('.').map(Number);
            versionParts[versionParts.length - 1] += 1;
            
            return {
                ...app,
                version: versionParts.join('.'),
                updateDate: new Date().toISOString().split('T')[0],
                // 随机增加一些下载量
                downloads: app.downloads + Math.floor(Math.random() * 1000) + 100
            };
        } else {
            // 即使不更新版本，也增加一些下载量
            return {
                ...app,
                downloads: app.downloads + Math.floor(Math.random() * 200) + 10
            };
        }
    });
    
    saveAppsData(updatedApps);
    console.log('应用信息更新完成');
}, 86400000); // 24小时（86400000毫秒）
